/*
 * $Id$
 */
package py.windmill.web;

import java.util.ArrayList;
import java.util.List;

import py.windmill.action.ActionSupport;
import py.windmill.action.MimeType;
import py.windmill.action.Request;
import py.windmill.action.Resolution;
import py.windmill.web.dict.DictionaryService;

import py.windmill.resolution.Forward;
import py.windmill.resolution.Tiles;
import py.windmill.resolution.TilesMap;

import py.windmill.web.dict.DictionaryServiceFactory;
import py.windmill.util.JsonObject_;

/**
 *
 * @author myang
 */
public class DictionaryAction extends ActionSupport {

    final private DictionaryService _ds = DictionaryServiceFactory.json();

    @Override
    public Object onGet(final Request req) {
        final String word = req.param("word");
        return (null == word
          || 0 == word.length()) ? null : _ds.selectWord(word, idx(req));
    }

    /**
     *
     * @param req
     * @return
     */
    private int idx(final Request req) {
        final int i = req.getInt("idx", 1) - 1;
        return i < 0 ? 0 : i;
    }

//    @Override
//    public ValidationErrors validate(final Request req) {
//        return validate(req, "word", new Required());
//    }
    @Override
    public String boundTo() {
        return "/dict/{word}[{idx=1}]";
    }

    /**
     *
     * @return
     */
    @Override
    public List<Resolution> produces() {
        final List<Resolution> resolutions = new ArrayList();
        resolutions.add(new Tiles() {

            @Override
            public boolean isAcceptedBy(final Request req) {
                return -1 == req.accepts(MimeType.JSON);
            }

            @Override
            public TilesMap prepare(final Request req, final Object val) {
                req.attr("word", JsonObject_.toString(val));
                return new TilesMap("page", "dict2.jsp");
            }
        });
        resolutions.addAll(super.produces());
        return resolutions;
    }
}
